<template>
  <div class="xtx-infinite-loading" ref="target">
    <div class="loading" v-if="loading">
      <span class="img"></span>
      <span class="text">正在加载...</span>
    </div>
    <div class="none" v-if="finished">
      <span class="img"></span>
      <span class="text">{{ finishedText }}</span>
    </div>
  </div>
</template>

<script>
/*
1:加载中时显示加载中字符
2：加载完成，要显示没有更多了
3：滚动到底部时调用方法加载数据
*/
import { useIntersectionObserver } from '@vueuse/core'
import { ref, watch } from 'vue'
export default {
  name: 'PullLoad',
  props: {
    loading: {
      type: Boolean,
      default: false
    },
    finished: {
      type: Boolean,
      default: false
    },
    finishedText: {
      type: String,
      default: '加载完了'
    }
  },
  setup (props, { emit }) {
    const target = ref(null)
    watch(
      () => props.loading,
      () => {
        if (!props.loading && !props.finished) {
          const { stop } = useIntersectionObserver(
            // target:需要监听的目标dom
            target,
            ([{ isIntersecting }], option) => {
              // isIntersecting:是否进入可视区域 true就是进入，false:没进入  options:读取当前配制
              if (isIntersecting) {
                // console.log('进入可视区域')
                if (!props.loading && !props.finished) {
                  stop()
                  emit('load')
                }
              }
            },
            // 设置配制
            { threshold: 0 }
          )
        }
      },
      {
        immediate: true
      }
    )

    return { target }
  }
}
</script>
<style scoped lang="less">
.xtx-infinite-loading {
  .loading {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 50px;
      height: 50px;
      background: url(~@/assets/images/load.gif) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
  .none {
    display: flex;
    align-items: center;
    justify-content: center;
    height: 200px;
    .img {
      width: 200px;
      height: 134px;
      background: url(~@/assets/images/none.png) no-repeat center / contain;
    }
    .text {
      color: #999;
      font-size: 16px;
    }
  }
}
</style>
